import { isObject } from "tdesign-miniprogram/common/src"
import { isString } from "tdesign-miniprogram/common/utils"

export function toCsvString<T extends Record<string, any>|null>(records: T[]): string {
  if (records.length == 0) {
    return ''
  }

  let lines: string[] = []
  for (let i = 0; i < records.length; i++) {
    if (!records[i]) {
      continue;
    }
    
    let keys: string[] = Object.keys(records[i]!).sort()
    let line: string[] = []
    keys.forEach(key => {
      let val = records[i]![key]
      if (val == null || val == undefined) {
        line.push('')
      } else if (isObject(val)) {
        line.push(csvSafeString(JSON.stringify(val)))
      } else if (isString(val)) {
        line.push(csvSafeString(val))
      } else {
        line.push(`${val}`)
      }
    })
    lines.push(line.join(','))
  }
  return lines.join("\n")
}

// 将字符串包裹在双引号内并将内部双引号转义
export function csvSafeString(str: string): string {
  return `"${str.replace('"', '""')}"`
}